//
//  CZCarInfoController.m
//  TCProject
//
//  Created by admin on 16/1/29.
//  Copyright © 2016年 wise-wing. All rights reserved.
//

#import "CZCarInfoController.h"
#import "ZDTruck.h"
#import "AccountManager.h"
#import <UIButton+WebCache.h>
#import "Spinner.h"


@interface CZCarInfoController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate> {
    UIButton *_uploadButton;
}
@property(nonatomic, weak) UITextField *carTF;
@property(nonatomic, weak) UIPickerView *pickerView;
@property(nonatomic, strong) TruckItem *currentItem;

@property(nonatomic, strong) Spinner *spinner;
@property(nonatomic, strong) NSArray *carStyles;

@property (weak, nonatomic) IBOutlet UIButton *carStyleButton;
@property (weak, nonatomic) IBOutlet UITextField *carOwnerTextField;
@property (weak, nonatomic) IBOutlet UITextField *carNumTextField;

@property (weak, nonatomic) IBOutlet UIButton *provinceButton;

@property (weak, nonatomic) IBOutlet UITextField *chejiaTextField;

@property (weak, nonatomic) IBOutlet UITextField *driverTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UIButton *picButton1;
@property (weak, nonatomic) IBOutlet UIButton *picButton2;
@property (weak, nonatomic) IBOutlet UIButton *picButton3;

@property (weak, nonatomic) IBOutlet UIButton *picButton4;

- (IBAction)chooseCarType:(UIButton *)sender;
- (IBAction)provinceAction:(id)sender;
- (IBAction)uploadImage:(id)sender;
- (IBAction)commitAction:(id)sender;



@end

@implementation CZCarInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.rowHeight = 44.f;
    
    UITextField *districtTF = [UITextField new];
    UIPickerView *inputView = [[UIPickerView alloc] init];
    inputView.delegate = self;
    inputView.dataSource = self;
    districtTF.inputView = inputView;
    districtTF.inputAccessoryView = [[[NSBundle mainBundle] loadNibNamed:@"InputToolbar" owner:self options:nil] firstObject];
    [self.view addSubview:districtTF];
    self.carTF = districtTF;
    self.pickerView = inputView;
    [self.chejiaTextField addTarget:self action:@selector(changeUpterStr:) forControlEvents:UIControlEventEditingChanged];
    [self.carNumTextField addTarget:self action:@selector(changeUpterStr:) forControlEvents:UIControlEventEditingChanged];
    
    [self getData];
    
    if (_car) {
        [self setModify];
    }

}



- (void)getData {
    BMRequest *request = [BMRequest requestWithPath:@"getTruckStyle.htm" contentKey:@"styles"];
    [self showHudWithhint:kDefaultMessage];
    [ZDTruck postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            self.carStyles = response.result;
        } else {
            [self showHint:response.msg];
        }
    }];
}

- (void)setModify {
    self.title = @"编辑车辆";
    
    [self.carStyleButton setTitle:[NSString stringWithFormat:@"%@--%@", _car.style1Name, _car.styleName] forState:UIControlStateNormal];
    self.carOwnerTextField.text = _car.truckOwner;
    self.carNumTextField.text = _car.licensePlateNum;
    [self.provinceButton setTitle:_car.licensePlate forState:UIControlStateNormal];
    self.chejiaTextField.text = _car.frameNum;
    self.driverTextField.text = _car.driver;
    self.phoneTextField.text = _car.phone;
    
    [self.picButton1 sd_setBackgroundImageWithURL:[NSURL URLWithString:_car.driveLic0] forState:UIControlStateSelected completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image != nil) {
            self.picButton1.selected = YES;
        }
    }];
    
    [self.picButton2 sd_setBackgroundImageWithURL:[NSURL URLWithString:_car.driveLic1] forState:UIControlStateSelected completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image != nil) {
            self.picButton2.selected = YES;
        }
    }];
    
    [self.picButton3 sd_setBackgroundImageWithURL:[NSURL URLWithString:_car.drivingLic0] forState:UIControlStateSelected completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image != nil) {
            self.picButton3.selected = YES;
        }
    }];
    
    [self.picButton4 sd_setBackgroundImageWithURL:[NSURL URLWithString:_car.drivingLic1] forState:UIControlStateSelected completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image != nil) {
            self.picButton4.selected = YES;
        }
    }];
}

- (IBAction)toolbarCancle:(id)sender {
    [self.carTF resignFirstResponder];
}

- (IBAction)toolbarOK:(id)sender {
    [self.carTF resignFirstResponder];
    NSInteger com1 = [self.pickerView selectedRowInComponent:0];
    NSInteger com2 = [self.pickerView selectedRowInComponent:1];
    TruckItem *item = [self.carStyles[com1] nextTruckList][com2];
    self.currentItem = item;
}

- (void)setCurrentItem:(TruckItem *)currentItem {
    _currentItem = currentItem;
    
    NSInteger com1 = [self.pickerView selectedRowInComponent:0];
    [self.carStyleButton setTitle:[NSString stringWithFormat:@"%@--%@", [_carStyles[com1] styleName], currentItem.styleName] forState:UIControlStateNormal];
    _car.style1 = _currentItem.ID;
}


- (IBAction)chooseCarType:(UIButton *)sender {
    [self.carTF becomeFirstResponder];

}

- (IBAction)provinceAction:(id)sender {
    [self.view endEditing:YES];
    [self.spinner show];
}

- (IBAction)uploadImage:(UIButton* )sender {
    if (sender.selected) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"是否删除当前照片" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:cancleAction];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [sender setBackgroundImage:nil forState:UIControlStateSelected];
            sender.selected = NO;
            if (sender == _picButton1) {
                _car.driveLic0 = nil;
            } else if (sender == _picButton2) {
                _car.driveLic1 = nil;
            } else if (sender == _picButton3) {
                _car.drivingLic0 = nil;
            } else if (sender == _picButton4) {
                _car.drivingLic1 = nil;
            }
        }];
        [alertVC addAction:okAction];
        //        [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
        //        [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
        [self presentViewController:alertVC animated:YES completion:nil];
        
    } else {
        _uploadButton = sender;
        UIAlertController *alertVC = [UIAlertController new];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *imageVC = [[UIImagePickerController alloc] init];
                imageVC.delegate = self;
                imageVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imageVC animated:YES completion:nil];
            } else {
                [self showHint:@"照相机不可用"];
            }
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"本地上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            UIImagePickerController *imageVC = [[UIImagePickerController alloc] init];
            imageVC.delegate = self;
            imageVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imageVC animated:YES completion:nil];
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }

}

- (IBAction)commitAction:(id)sender {
    if (_car) {
        [self updateTruckTask];
    } else {
        [self addTruckTask];
    }

}

- (void)updateTruckTask {
    _car.truckOwner = _carOwnerTextField.text;
    _car.licensePlateNum = _carNumTextField.text;;
    _car.frameNum = _chejiaTextField.text;
    _car.driver = _driverTextField.text;
    _car.phone = _phoneTextField.text;
    
    if (!_car.style1) {
        [self showHint:@"请选择车辆类型"];
        return;
    }
    
    if ([BMUtils isEmptyString:_car.truckOwner]) {
        [self showHint:@"请填写车辆所有人"];
        return;
    }
    
    if ([BMUtils isEmptyString:_car.licensePlateNum]) {
        [self showHint:@"请填写车牌号"];
        return;
    }
    
    if ([BMUtils isEmptyString:_car.frameNum]) {
        [self showHint:@"请填写车架号"];
        return;
    }
    
    if ([BMUtils isEmptyString:_car.driver]) {
        [self showHint:@"请填写随车司机"];
        return;
    }
    
    if ([BMUtils isEmptyString:_car.phone]) {
        [self showHint:@"请填写随车电话"];
        return;
    }
    
    if (![BMUtils isValidateCarNo:_car.licensePlateNum]) {
        [self showHint:@"请填写有效地车牌号码"];
        return;
    }
    
    if (_car.frameNum.length != 6) {
        [self showHint:@"请填写有效地车架号码"];
        return;
    }
    
    if (![BMUtils isValidateMobile:_car.phone]) {
        [self showHint:@"请填写有效地手机号码"];
        return;
    }
    
    
    if (!_picButton1.isSelected || !_picButton2.isSelected || !_picButton3.isSelected || !_picButton4.isSelected) {
        [self showHint:@"请上传所有有效附件"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (_picButton1.tag && _picButton1.isSelected && _picButton1.currentBackgroundImage) {
        params[@"pic1"] = UIImageJPEGRepresentation(_picButton1.currentBackgroundImage, 0.1);
    }
    if (_picButton2.tag && _picButton2.isSelected && _picButton2.currentBackgroundImage) {
        params[@"pic2"] = UIImageJPEGRepresentation(_picButton2.currentBackgroundImage, 0.1);
    }
    if (_picButton3.tag && _picButton3.isSelected && _picButton3.currentBackgroundImage) {
        params[@"pic3"] = UIImageJPEGRepresentation(_picButton3.currentBackgroundImage, 0.1);
    }
    if (_picButton4.tag && _picButton4.isSelected && _picButton4.currentBackgroundImage) {
        params[@"pic4"] = UIImageJPEGRepresentation(_picButton4.currentBackgroundImage, 0.1);
    }
    
    if (params.count) { //用户重新上传了;
        BMRequest *request = [BMRequest requestWithPath:@"uploadImg.htm"];
        request.uploadData = params;
        [self showHudWithhint:kDefaultMessage];
        [[BMHttpTool sharedInstance] uploadWith:request finish:^(BMResponse *response, NSError *error) {
            [self hideHud];
            if (response.status == kResultOK) {
                NSString *driveLic0 = response.rawResult[@"pic1"];
                if (driveLic0) {
                    _car.driveLic0 = driveLic0;
                }
                NSString *driveLic1 = response.rawResult[@"pic2"];
                if (driveLic1) {
                    _car.driveLic1 = driveLic1;
                }
                NSString *drivingLic0 = response.rawResult[@"pic3"];
                if (drivingLic0) {
                    _car.drivingLic0 = drivingLic0;
                }
                NSString *drivingLic1 = response.rawResult[@"pic4"];
                if (drivingLic1) {
                    _car.drivingLic1 = drivingLic1;
                }
                [self updateInfo];
            } else {
                [self showHint:@"上传证件失败!"];
            }
        }];
    } else {
        [self updateInfo];
    }
}

- (void)updateInfo {
    BMRequest *request = [BMRequest requestWithPath:@"update.htm"];
    request.params = @{@"id" : @(_car.ID),
                       @"style1" : @(_car.style1),
                       @"truckOwner" : _car.truckOwner,
                       @"licensePlate" : _car.licensePlate,
                       @"licensePlateNum" : _car.licensePlateNum,
                       @"frameNum" : _car.frameNum,
                       @"driver" : _car.driver,
                       @"phone" : _car.phone,
                       @"driveLic0" : _car.driveLic0 ? _car.driveLic0 : @"",
                       @"driveLic1" : _car.driveLic1 ? _car.driveLic1 : @"",
                       @"drivingLic0" : _car.drivingLic0 ? _car.drivingLic0 : @"",
                       @"drivingLic1" : _car.drivingLic1 ? _car.drivingLic1 : @""};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            [self showHint:@"修改车辆信息成功"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self showHint:response.msg];
        }
    }];
}

/**
 *  添加车辆
 */
- (void)addTruckTask {
    NSString *truckOwner = _carOwnerTextField.text;
    NSString *licensePlateNum = _carNumTextField.text;
    
    NSString *frameNum = _chejiaTextField.text;
    
    NSString *driver = _driverTextField.text;
    NSString *phone = _phoneTextField.text;
    
    
    if (!_currentItem) {
        [self showHint:@"请选择车辆类型"];
        return;
    }
    
    if ([BMUtils isEmptyString:truckOwner]) {
        [self showHint:@"请填写车辆所有人"];
        return;
    }
    
    if ([BMUtils isEmptyString:licensePlateNum]) {
        [self showHint:@"请填写车牌号"];
        return;
    }
    
    if ([BMUtils isEmptyString:frameNum]) {
        [self showHint:@"请填写车架号"];
        return;
    }
    
    if ([BMUtils isEmptyString:driver]) {
        [self showHint:@"请填写随车司机"];
        return;
    }
    
    if ([BMUtils isEmptyString:phone]) {
        [self showHint:@"请填写随车电话"];
        return;
    }
    
    if (![BMUtils isValidateCarNo:licensePlateNum]) {
        [self showHint:@"请填写有效地车牌号码"];
        return;
    }
    
    if (frameNum.length != 6) {
        [self showHint:@"请填写有效地车架号码"];
        return;
    }
    
    if (![BMUtils isValidateMobile:phone]) {
        [self showHint:@"请填写有效地手机号码"];
        return;
    }
    
    if (!_picButton1.isSelected || !_picButton2.isSelected || !_picButton3.isSelected || !_picButton4.isSelected) {
        [self showHint:@"请上传所有有效附件"];
        return;
    }
    
    NSMutableDictionary *images = [NSMutableDictionary dictionary];
    if (_picButton1.isSelected && _picButton1.currentBackgroundImage) {
        images[@"pic1"] = UIImageJPEGRepresentation(_picButton1.currentBackgroundImage, 0.1);
    }
    if (_picButton2.isSelected && _picButton2.currentBackgroundImage) {
        images[@"pic2"] = UIImageJPEGRepresentation(_picButton2.currentBackgroundImage, 0.1);
    }
    if (_picButton3.isSelected && _picButton3.currentBackgroundImage) {
        images[@"pic3"] = UIImageJPEGRepresentation(_picButton3.currentBackgroundImage, 0.1);
    }
    if (_picButton4.isSelected && _picButton4.currentBackgroundImage) {
        images[@"pic4"] = UIImageJPEGRepresentation(_picButton4.currentBackgroundImage, 0.1);
    }
    
    if (images.count) {
        BMRequest *request = [BMRequest requestWithPath:@"uploadImg.htm"];
        request.uploadData = images;
        [self showHudWithhint:kDefaultMessage];
        [[BMHttpTool sharedInstance] uploadWith:request finish:^(BMResponse *response, NSError *error) {
            [self hideHud];
            if (response.status == kResultOK) {
                [self addCar:truckOwner licensePlateNum:licensePlateNum frameNum:frameNum driver:driver phone:phone response:response];
            } else {
                [self showHint:response.msg];
            }
        }];
    } else {
        [self addCar:truckOwner licensePlateNum:licensePlateNum frameNum:frameNum driver:driver phone:phone response:nil];
    }
}

- (void)addCar:(const NSString *)truckOwner licensePlateNum:(const NSString *)licensePlateNum frameNum:(const NSString *)frameNum driver:(const NSString *)driver phone:(const NSString *)phone response:(const BMResponse *)response {
    BMRequest *request = [BMRequest requestWithPath:@"add.htm"];
    request.params = @{@"owerId" : @([AccountManager sharedInstance].user.ID),
                       @"style1" : @(_currentItem.ID),
                       @"truckOwner" : truckOwner,
                       @"licensePlate" : _provinceButton.currentTitle,
                       @"licensePlateNum" : licensePlateNum,
                       @"frameNum" : frameNum,
                       @"driver" : driver,
                       @"phone" : phone};
    if (response) {
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:request.params];
        NSString *driveLic0 = [response.rawResult valueForKey:@"pic1"];
        NSString *driveLic1 = [response.rawResult valueForKey:@"pic2"];
        NSString *drivingLic0 = [response.rawResult valueForKey:@"pic3"];
        NSString *drivingLic1 = [response.rawResult valueForKey:@"pic4"];
        if (![BMUtils isEmptyString:driveLic0]) {
            params[@"driveLic0"] = driveLic0;
        }
        if (![BMUtils isEmptyString:driveLic1]) {
            params[@"driveLic1"] = driveLic1;
        }
        if (![BMUtils isEmptyString:drivingLic0]) {
            params[@"drivingLic0"] = drivingLic0;
        }
        if (![BMUtils isEmptyString:drivingLic1]) {
            params[@"drivingLic1"] = drivingLic1;
        }
        request.params = params;
    }
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        if (response.status == kResultOK) {
            [self showHint:@"已添加，等待审核中…"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self showHint:response.msg];
        }
    }];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info; {
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        image = [image fixOrientation];
        _uploadButton.selected = YES;
        _uploadButton.tag = 1;
        [_uploadButton setBackgroundImage:image forState:UIControlStateSelected];
    }];
}

#pragma mark - UIPickerView

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView; {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return _carStyles.count;
    } else if (component == 1) {
        return [_carStyles[[pickerView selectedRowInComponent:0]] nextTruckList].count;
    }
    return 0;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *pickerLabel = (UILabel *) view;
    if (!pickerLabel) {
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textColor = [UIColor darkGrayColor];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setFont:[UIFont systemFontOfSize:14.f]];
    }
    // Fill the label text here
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [_carStyles[row] styleName];
    } else if (component == 1) {
        TruckItem *item = [_carStyles[[pickerView selectedRowInComponent:0]] nextTruckList][row];
        return item.styleName;
    }
    return @"";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:NO];
    }
}


- (Spinner *)spinner {
    if (!_spinner) {
        weakSelf(self);
        _spinner = [[Spinner alloc] init];
        _spinner.datas = @[@"冀", @"豫", @"云", @"辽", @"黑", @"湘", @"皖", @"鲁", @"新", @"苏", @"浙", @"赣", @"鄂", @"桂", @"甘", @"晋", @"蒙", @"陕", @"吉", @"闽", @"贵", @"粤", @"青", @"藏", @"川", @"宁", @"琼", @"渝", @"京", @"津", @"沪"];
        [_spinner setSelected:^(NSIndexPath *indexPath) {
            [weakSelf.provinceButton setTitle:weakSelf.spinner.datas[indexPath.row] forState:UIControlStateNormal];
            weakSelf.car.licensePlate = weakSelf.spinner.datas[indexPath.row];
        }];
    }
    return _spinner;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == _carNumTextField) {
        if (range.length == 0 && textField.text.length > 5) {
            return NO;
        }
    } else if (textField == _chejiaTextField) {
        if (range.length == 0 && textField.text.length > 5) {
            return NO;
        }
    } else if (textField == _phoneTextField) {
        if (range.length == 0 && textField.text.length > 10) {
            return NO;
        }
    }
    return YES;
}

- (void)changeUpterStr:(UITextField *)textField {
    textField.text = [textField.text uppercaseString];
}

@end
